/*
 * UserDAO.java
 *
 * Created on 3 marzec 2007, 12:39
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package arocms.business;

import arocms.util.HibernateUtil;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Session;

/**
 *
 * @author arek
 */
public class UserDAO implements DaoMethods<User>{
    
    private final Logger log = Logger.getLogger(this.getClass());
    
    /** Creates a new instance of UserDAO */
    public UserDAO() {
    }
    
    public  List<User> findAll() {
        log.debug("--> findAll");
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List<User> aListOfUsers = (List<User>) session.createQuery("From User").list();
        session.getTransaction().commit();
        log.debug("<-- findAll");
        return aListOfUsers;
    }
    
    public  User find(Long pk) {
        log.debug("--> find");
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        User aUser = (User) session.load(User.class, pk);
        session.getTransaction().commit();
        log.debug("<-- find");
        return aUser;
    }
    
    public  boolean delete(Long pk) {
        log.debug("-> delete");
        log.debug("Deleting user with pk = " + pk);
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.delete(session.load(User.class,pk));
        session.getTransaction().commit();
        log.debug("<- delete");
        return true;
    }
    
    public  User update(User aUser) {
        log.debug("--> update");
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.update(aUser);
        session.getTransaction().commit();
        log.debug("<-- delete");
        return aUser;
    }
    
    public  User create(User aUser){
        log.debug("--> create");
        aUser.setId(null);
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.persist(aUser);
        session.getTransaction().commit();
        log.debug("--> create");
        return aUser;
    }

    public User createOrUpdate(User obj) {
        log.debug("--> createOrUpdate");
        if (obj.getId()==null || obj.getId()==0) {
            log.debug("<-- createOrUpdate, before create, ID = " + obj.getId());
            return create(obj);
        } else {
            log.debug("<-- createOrUpdate, before update");
            return update(obj);
        }
        
    }

    public boolean delete(User obj) {
        return delete(obj.getId());
    }
}
